﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Tracker.Domain.Entities;
using Tracker.Domain.DTOs;
using Tracker.Services.Abstract;
using Tracker.Data.Repository;
using Tracker.Data.UnitOfWork;

namespace Tracker.Services.Implementation
{
    public class PositionService : Service<Position>, IPositionService
    {
        private readonly IRepository<User> _userRepository;

        public PositionService(IRepository<Position> repository,
                               IRepository<User> userRepository,
                               IUnitOfWork unitOfWork)
            : base(repository, unitOfWork)
        {
            _userRepository = userRepository;
        }

        public void Add(PositionDTO dto)
        {
            var position = new Position();
            position.Latitude = dto.Latitude;
            position.Longitude = dto.Longitude;
            position.InsertDate = DateTime.Now;
            position.User = _userRepository.Get(x => x.ID == dto.UserID);
            position.Address = new Address();
            position.Address.Address1 = dto.Address1;
            position.Address.Address2 = dto.Address2;
            position.Address.City = dto.City;
            position.Address.State = dto.State;
            position.Address.Zip = dto.Zip;
            dto.ID = base.Add(position);
        }

        public void Update(PositionDTO dto)
        {
            var position = Single(x => x.ID == dto.ID);

            if (position != null)
            {
                position.Latitude = dto.Latitude;
                position.Longitude = dto.Longitude;
                position.User = _userRepository.Get(x => x.ID == dto.UserID);
                Save();
            }
        }

        public PositionDTO Get(int id)
        {
            return Single(x => x.ID == id).Map();
        }

        public PositionDTO Get(Expression<Func<Position, bool>> predicate)
        {
            return Single(predicate).Map();
        }

        public IList<PositionDTO> GetAll()
        {
            return All().Map();
        }

        public IList<PositionDTO> GetAll(Expression<Func<Position, bool>> predicate)
        {
            return All(predicate).Map();
        }
    }
}
